/*
 * 	Copyright © OpenAtom Foundation.
 * 	Licensed under the Apache License, Version 2.0 (the "License");
 * 	you may not use this file except in compliance with the License.
 * 	You may obtain a copy of the License at
 * 	     http://www.apache.org/licenses/LICENSE-2.0
 * 	Unless required by applicable law or agreed to in writing, software
 * 	distributed under the License is distributed on an "AS IS" BASIS,
 * 	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * 	See the License for the specific language governing permissions and
 * 	limitations under the License.
 *
 */

package com.inspur.edp.sgf.api.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import com.inspur.edp.caf.transaction.api.GlobalTransactionService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 功能描述: @ClassName: EapiServiceUtils @Author: Fynn Qi @Date: 2019/10/22 16:04 @Version: V1.0
 */
public class EapiServiceUtils {

    /**
     * 参数忽略大小写处理
     *
     * @param fieldName
     * @param node
     * @return
     */
    public static JsonNode getJsonNodeIgnoreCase(String fieldName, JsonNode node) {
        if (Objects.isNull(fieldName) || Objects.isNull(node)) {
            return null;
        }
        Iterator<String> fieldNames = node.fieldNames();
        if (fieldNames == null || node.size() <= 0) {
            return null;
        }
        List<String> list = Lists.newArrayList(fieldNames).stream().filter(x -> x.trim().equalsIgnoreCase(fieldName.trim())).collect(Collectors.toList());
        return list.size() <= 0 ? null : node.get(list.get(0));
    }

    /**
     * 转JsonNode
     *
     * @param fromValue
     * @return
     */
    public static JsonNode valueToTree(Object fromValue) {
        return ObjectMapperUtil.valueToTree(fromValue);
    }

    /**
     * 获取分布式事务Bean
     *
     * @return
     */
    public static GlobalTransactionService getGlobalTransactionService() {
        return GlobalTransactionServiceInstance.globalTransactionService;
    }

    private static class GlobalTransactionServiceInstance {
        static GlobalTransactionService globalTransactionService = SpringBeanUtils.getBean(GlobalTransactionService.class);
    }
}
